﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;

namespace Pay.Service.Service {
    public class TopicService : ServiceBase, ITopicService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IMerchantService _iMerchantService;

        public TopicService(IUnitOfWork iUnitOfWork, IMerchantService iMerchantService)
             : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iMerchantService = iMerchantService;
        }


        #region 专题
        /// <summary>
        /// 获取专题列表
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="query">Identifier.</param>
        public PagedResult<topic_dto> GetTopics(TopicQuery query) {
            var filter = PredicateBuilder.True<Topic>();
            if (query.merchant_id > 0)
                filter = filter.And(c => c.MerchantId == query.merchant_id);
            if (query.show_type > 0)
                filter = filter.And(c => c.ShowType == query.show_type);
            var result = context.Topics.FromCachePaged<Topic, topic_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.Id), "Topic");
            return result;
        }
        public List<topic_dto> GetTopicList(TopicQuery query) {
            var linq = from topic in context.Topics select topic;
            if (query.merchant_id > 0)
                linq = linq.Where(x => x.MerchantId == query.merchant_id);
            if (query.show_type > 0)
                linq = linq.Where(x => x.ShowType == query.show_type);

            var result = linq.FromCache<Topic, topic_dto>("Topic");
            return result;
        }
        /// <summary>
        /// 获取专题列表--app端
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="model">Identifier.</param>
        public List<topic_list> GetGroup(topic_query_index model) {
            var list = context.Topics.Where(c => c.ShowType == model.show_type).FromCache<Topic, topic_dto>("Topic");
            List<topic_list> result = new List<topic_list>();
            foreach (var item in list) {
                var topic = new topic_list {
                    id = item.id, page_type = item.page_type, remark = item.remark,
                    show_images = item.show_images, show_type = item.show_type, title = item.title
                };

                if (model.number > 0) {
                    topic.goods = item.topic_groups.SelectMany(c => c.topic_products).Take(model.number).Select(c => c.product).ToList();
                }
                result.Add(topic);
            }
            return result;
        }

        /// <summary>
        /// 获取专题信息
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="id">Identifier.</param>
        public topic_dto GetTopic(long id) {
            var topic = context.Topics.Where(c => c.Id == id).FromCacheFirstOrDefault<Topic, topic_dto>("Topic");
            return topic;
        }

        /// <summary>
        /// 编辑专题信息
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="dto">Identifier.</param>
        public int AlterTopic(topic_dto dto) {
            foreach (var groups in dto.topic_groups) {
                foreach (var product in groups.topic_products) {
                    product.product = null;
                }
            }
            var model = context.Topics.FirstOrDefault(c => c.Id == dto.id);
            var topic = dto.ToDtoObject<Topic>();

            //专题修改
            model.Title = topic.Title;
            model.ShowImages = topic.ShowImages;
            model.ShowType = topic.ShowType;
            model.Banner = topic.Banner;
            model.PageType = topic.PageType;
            model.CreateTime = topic.CreateTime;
            model.Remark = topic.Remark;

            //专题分组
            if (topic.TopicGroups.Count > 0) {
                var req_ids = topic.TopicGroups.Select(c => c.Id).CopyToList();
                var data_ids = model.TopicGroups.Select(c => c.Id).CopyToList();
                //分组新增
                req_ids.Except(data_ids).DataForEach(filter_id => {
                    var item_group = topic.TopicGroups.First(c => c.Id == filter_id);
                    //商品新增
                    //item_group.TopicProducts.ForEach(product => {
                    //    model_item.TopicProducts.Add(product.ToDtoObject<TopicProduct>());
                    //});
                    model.TopicGroups.Add(item_group);
                });
                //分组删除
                data_ids.Except(req_ids).DataForEach(filter_id => {
                    var item_group = model.TopicGroups.First(c => c.Id == filter_id);
                    //商品删除
                    item_group.TopicProducts.DataForEach(product => {
                        context.Entry(product).State = EntityState.Deleted;
                    });
                    context.Entry(item_group).State = EntityState.Deleted;
                });
                //分组更新
                req_ids.Intersect(data_ids).DataForEach(filter_id => {
                    var item_group = topic.TopicGroups.First(c => c.Id == filter_id);
                    var model_group = model.TopicGroups.First(c => c.Id == filter_id);
                    model_group.Name = item_group.Name;
                    model_group.ShowImages = item_group.ShowImages;

                    //商品增删改
                    var req_pids = item_group.TopicProducts.Select(c => c.ProductId).CopyToList();
                    var data_pids = model_group.TopicProducts.Select(c => c.ProductId).CopyToList();
                    //商品新增
                    req_pids.Except(data_pids).DataForEach(filter_pid => {
                        var pitem = item_group.TopicProducts.First(c => c.ProductId == filter_pid);
                        model_group.TopicProducts.Add(pitem);
                    });
                    //商品删除
                    data_pids.Except(req_pids).DataForEach(filter_pid => {
                        var item_product = model_group.TopicProducts.First(c => c.ProductId == filter_pid);
                        context.Entry(item_product).State = EntityState.Deleted;
                    });
                    //商品更新
                    //req_pids.Intersect(data_pids).DataForEach(filter_pid => {
                    //    var pitem = item_group.TopicProducts.First(c => c.Id == filter_pid);
                    //    var pmodel_item = model_group.TopicProducts.First(c => c.Id == filter_pid);

                    //    context.Entry(pmodel_item).State = EntityState.Modified;
                    //});
                    context.Entry(model_group).State = EntityState.Modified;
                });
            } else {
                model.TopicGroups.DataForEach((model_item, i) => {
                    model_item.TopicProducts.DataForEach((pro_item, j) => {
                        context.Entry(pro_item).State = EntityState.Deleted;
                    });
                    context.Entry(model_item).State = EntityState.Deleted;
                });
            }

            //dto.ToDtoObject(model);
            //分组
            //if (dto.topic_groups.Count > 0) {
            //    var req_ids = dto.topic_groups.Select(c => c.id).ToList();
            //    var data_ids = model.TopicGroups.Select(c => c.Id).CopyToList();
            //    //新增
            //    req_ids.Except(data_ids).DataForEach(filter_id => {
            //        var item = dto.topic_groups.First(c => c.id == filter_id);
            //        var model_item = item.ToDtoObject<TopicGroup>();
            //        //商品新增
            //        item.topic_products.ForEach(product => {
            //            model_item.TopicProducts.Add(product.ToDtoObject<TopicProduct>());
            //        });
            //        model.TopicGroups.Add(model_item);
            //    });
            //    //删除
            //    data_ids.Except(req_ids).DataForEach(filter_id => {
            //        var model_item = model.TopicGroups.First(c => c.Id == filter_id);
            //        //商品删除
            //        model_item.TopicProducts.DataForEach(product => {
            //            context.Entry(product).State = EntityState.Deleted;
            //        });
            //        context.Entry(model_item).State = EntityState.Deleted;
            //    });
            //    //更新
            //    req_ids.Intersect(data_ids).DataForEach(filter_id => {
            //        var item = dto.topic_groups.First(c => c.id == filter_id);
            //        var model_item = model.TopicGroups.First(c => c.Id == filter_id);
            //        var gid = model_item.Id;
            //        item.ToDtoObject(model_item);
            //        model_item.Id = gid;
            //        #region 商品增删改
            //        var req_pids = item.topic_products.Select(c => c.id).ToList();
            //        var data_pids = model_item.TopicProducts.Select(c => c.Id).CopyToList();
            //        //新增
            //        req_pids.Except(data_pids).DataForEach(filter_pid => {
            //            var pitem = item.topic_products.First(c => c.id == filter_pid);
            //            var pmodel_item = pitem.ToDtoObject<TopicProduct>();
            //            model_item.TopicProducts.Add(pmodel_item);
            //        });
            //        //删除
            //        data_pids.Except(req_pids).DataForEach(filter_pid => {
            //            var pmodel_item = model_item.TopicProducts.First(c => c.Id == filter_pid);
            //            context.Entry(pmodel_item).State = EntityState.Deleted;
            //        });
            //        //更新
            //        req_pids.Intersect(data_pids).DataForEach(filter_pid => {
            //            var pitem = item.topic_products.First(c => c.id == filter_pid);
            //            var pmodel_item = model_item.TopicProducts.First(c => c.Id == filter_pid);
            //            var pid = pmodel_item.Id;
            //            pitem.ToDtoObject(pmodel_item);
            //            pmodel_item.Id = pid;
            //            context.Entry(pmodel_item).State = EntityState.Modified;
            //        });
            //        #endregion
            //        context.Entry(model_item).State = EntityState.Modified;
            //    });
            //} else {
            //    model.TopicGroups.DataForEach((model_item, i) => {
            //        model_item.TopicProducts.DataForEach((pro_item, j) => {
            //            context.Entry(pro_item).State = EntityState.Deleted;
            //        });
            //        context.Entry(model_item).State = EntityState.Deleted;
            //    });
            //}

            int result = _iUnitOfWork.Commit("Topic");
            return result;
        }

        /// <summary>
        /// 保存专题信息
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="dto">Identifier.</param>
        public int SaveTopic(topic_dto dto) {
            foreach (var groups in dto.topic_groups) {
                foreach (var product in groups.topic_products) {
                    product.product = null;
                }
            }
            var model = dto.ToDtoObject<Topic>();
            //分组
            //dto.topic_groups.ForEach(group => {
            //	var groupModel = group.ToDtoObject<TopicGroup>();
            //	//商品
            //	group.topic_products.ForEach(product => {
            //		groupModel.TopicProducts.Add(product.ToDtoObject<TopicProduct>());
            //	});
            //	model.TopicGroups.Add(groupModel);
            //});
            context.Topics.Add(model);
            var result = _iUnitOfWork.Commit("Topic");
            return result;
        }

        /// <summary>
        /// 保存/编辑专题信息=-应用端
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="dto">Identifier.</param>
        public ApiResultMessage Save(topic_model dto) {
            int result = 0;
            var model = dto.ToDtoObject<topic_dto>();
            model.create_time = DateTime.Now;
            var user = _iMerchantService.Get(dto.bind_no);
            model.merchant_id = user.id;
            if (dto.id > 0)
                result = AlterTopic(model);
            else
                result = SaveTopic(model);
            return ApiResultToJson.Success("保存成功");
        }

        /// <summary>
        /// 删除专题信息
        /// </summary>
        /// <returns>The verifyed.</returns>
        /// <param name="id">Identifier.</param>
        public int DeleteTopic(long id) {
            //删除专题
            context.Topics.Remove(id);
            //删除专题分组
            context.TopicGroups.Remove(c => c.TopicId == id);
            //删除专题分组商品 
            foreach (var group in context.TopicGroups.Where(c => c.TopicId == id).ToList())
                context.TopicProducts.Remove(c => c.GroupId == group.Id);
            var result = _iUnitOfWork.Commit("Topic");
            return result;
        }
        #endregion
    }
}
